#include "serialportset.h"
#include "ui_serialportset.h"

SerialPortSet::SerialPortSet(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SerialPortSet)
{
    ui->setupUi(this);

    //获取可用的串口信息
    QList<QSerialPortInfo> list =  QSerialPortInfo::availablePorts();
    for(const auto & port:list)
    {
        ui->portNameBox->addItem(port.portName());
    }
}

SerialPortSet::~SerialPortSet()
{
    delete ui;
}

void SerialPortSet::setDataDisplayTable()
{
    QTableWidget *table = new QTableWidget;
    connect(this, &SerialPortSet::dataReceived, [=](const QString& data) {
            int row = table->rowCount();
            table->insertRow(row);
            table->setItem(row, 0, new QTableWidgetItem(data));
        });
}


void SerialPortSet::on_openSerialPortButton_clicked()
{
    //配置相关的串口信息，串口名称 波特率...
    port = new QSerialPort(this);
    port->setPortName(ui->portNameBox->currentText());
    port->setBaudRate(ui->bautBox->currentText().toInt());

    if(ui->dataBox->currentText() == "8")
    {
        port->setDataBits(QSerialPort::Data8);
    }
    port->setStopBits(QSerialPort::OneStop);
    port->setFlowControl(QSerialPort::NoFlowControl);
    port->setParity(QSerialPort::NoParity);

    //打开串口
    bool isOpen = port->open(QIODevice::ReadWrite);
    if(!isOpen)
    {
        QMessageBox::critical(this,"错误","串口打开失败",QMessageBox::Ok);
        return;
    }

    //打开成功，读取数据
    connect(port,&QSerialPort::readyRead,[=](){
        ui->textEdit->append(port->readAll());
    });

}

void SerialPortSet::on_closeSerialPortButton_clicked()
{
    port = new QSerialPort(this);
    if(!port->isOpen())
    {
        port->close();
        QMessageBox::information(this,"关闭","串口已关闭",QMessageBox::Ok);
        return;
    }else
    {
        QMessageBox::warning(this,"关闭","没有打开的串口，无需关闭",QMessageBox::Ok);
    }
}
